package com.yungu.swift.admin.handler;

import com.yungu.swift.admin.base.HttpServletRequestWrapper;
import com.yungu.swift.utils.StringUtils;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.nio.charset.Charset;

import static com.yungu.swift.admin.config.NacosListener.SYS_CONFIG;

/**
 * 去掉图片前缀处理器，仅支持 @RequestBody 的形式
 *
 * @author : cuixiuyin
 * @date : 2019/7/11
 */
public class ImgPrefixHandler extends HandlerInterceptorAdapter {


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (request instanceof HttpServletRequestWrapper) {
            HttpServletRequestWrapper requestWrapper = (HttpServletRequestWrapper) request;
            String bodyStr = getBodyString(requestWrapper.getReader());
            String removeBodyStr = StringUtils.remove(bodyStr, SYS_CONFIG.getWebSite());
            requestWrapper.setBody(removeBodyStr.getBytes(Charset.forName("UTF-8")));
        }
        return super.preHandle(request, response, handler);
    }

    private String getBodyString(BufferedReader br) throws IOException {
        StringBuilder buffer = new StringBuilder();
        String line;
        while ((line = br.readLine()) != null) {
            buffer.append(line);
        }
        br.close();
        return buffer.toString();
    }
}
